# python-pptx 用户自动化生成和更新.pptx文件

import pptx
from pptx.util import Inches, Pt
from pptx.enum.shapes import MSO_SHAPE_TYPE
from pptx.dml.color import RGBColor
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE
from pptx.enum.chart import XL_LEGEND_POSITION

# 创建演示稿对象
prs = pptx.Presentation()


# 写入， 幻灯片布局模板
slide = prs.slides.add_slide(prs.slide_layouts[0])
prs.slides.add_slide(prs.slide_layouts[1])
prs.slides.add_slide(prs.slide_layouts[2])

# 删除幻灯片
print(len(prs.slides))
# del prs.slides._sldIdLst[0]
# del prs.slides._sldIdLst[1]
# del prs.slides._sldIdLst[2]
print(len(prs.slides))

# Inches 英寸
text = slide.shapes.add_textbox(Inches(5), Inches(1), Inches(1), Inches(1))
text.text = "我是文本"
p = text.text_frame.add_paragraph()
p.text = "我是段落"
p.add_run().text = "我是追加内容"
title_shape = slide.shapes.title
title_shape.text = "标题1"
slide.shapes.placeholders[1].text = "标题2"

# 添加自选图形
shape = slide.shapes.add_shape(MSO_SHAPE_TYPE.AUTO_SHAPE, Inches(3), Inches(1), Inches(1), Inches(1))
# 填充、边框
fill = shape.fill
fill.solid()
fill.fore_color.rgb = RGBColor(255, 0, 0)
line = shape.line
line.color.rgb = RGBColor(55, 3, 5)
line.width = Pt(2)

# 添加表格
table = slide.shapes.add_table(3, 3, Inches(1), Inches(1), Inches(1.9), Inches(1)).table
# 填充表格
table.cell(0, 0).text = "1"
table.cell(0, 1).text = "1"
table.cell(0, 2).text = "1"
table.cell(1, 0).text = "id"
table.cell(1, 1).text = "name"
table.cell(1, 2).text = "age"
table.cell(2, 0).text = "1"
table.cell(2, 1).text = "rich"
table.cell(2, 2).text = "21"
# 合并单元格
cell1 = table.cell(0, 0)
cell2 = table.cell(0, 2)
cell1.merge(cell2)
table.cell(0, 0).text = "个人信息"
print("单元格是否合并：", cell1.is_merge_origin)
# 取消合并
cell1.split()
print("取消合并后，单元格是否合并：", cell1.is_merge_origin)

# 写入图表
chart_data = CategoryChartData()
# x轴
chart_data.categories = ["一月", "二月", "三月"]
# y轴
chart_data.add_series("Y2020", (300, 400, 500))
chart_data.add_series("Y2019", (200, 500, 900))
# XL_CHART_TYPE.COLUMN_CLUSTERED 直方图
chart = slide.shapes.add_chart(XL_CHART_TYPE.LINE, Inches(1), Inches(4), Inches(3), Inches(3), chart_data).chart
chart.has_title = True
chart.chart_title.text_frame.text = "第一季度销售额"
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.RIGHT

# 保存
prs.save("test.pptx")
